﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

namespace KPWeb.Kontrolki
{
    public enum FormatRaportu : int
    {
        Brak = 0,
        Word = 1,
        Excel = 2,
        PDF = 3
    };

    public class RaportLinkButton : LinkButton
    {
        public string NazwaRaportu
        {
            get
            {
                string s = ViewState["DN"] as string;
                return s ?? "";
            }

            set { ViewState["DN"] = value; }
        }
        public bool DodajKieruenkID { get; set; }
        public bool DodajStudentID { get; set; }
        public bool DodajWydzialID { get; set; }
        bool dodajStudentStudiaID = false;
        public bool DodajStudentStudiaID { get { return dodajStudentStudiaID; } set { dodajStudentStudiaID = value; } }
        public bool PolaczWieczoroweZDziennymi { get; set; }
        public string DodatkowePrametry { get
            {
                string s = ViewState["DP"] as string;
                return s ?? "";
            }

            set { ViewState["DP"] = value; }
        }
        public FormatRaportu Format
        {
            get;
            set;
        }
        public bool RaportPensum { get; set; }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //if (!Page.IsPostBack)
            //{
            //    this.Attributes["onclick"] = string.Format("javascript:window.open('{0}{1}&rs:Command=Render&rs:ClearSession=true{2}{3}{4}')",
            //        DziekSysPage.DziekanatyRaportyUrl,
            //        NazwaRaportu, PobieraczRaportów.FormatRaportuText(Format),
            //        DodajKieruenkID ? string.Format("&KierunekID={0}", DziekSysPage.Current.KierunekID.ToString()) : string.Empty,
            //        DodajStudentID ? string.Format("&StudentID={0}", DziekSysPage.Current.StudentID.ToString()) : string.Empty);
            //}
        }
        public string UrlRaportu
        {
            get
            {
               // DodatkowePrametry = "DokumentNr=10/11/02736/u/st/IIWL&Slownie=sto dwadzieścia";

                //Dodac w WEB.config
                //string RaportyUrl =System.Configuration.ConfigurationManager.AppSettings["cPathToRaport"]
           // string RaportyUrl = "../Reports/";
              string NazwaRaportu = "WniosekUrlop";
              string RaportyUrl = "http://localhost:8620/Reports/";
              return string.Format("{0}{1}&rs:Command=Render&rs:ClearSession=true{2}{3}",
                        RaportyUrl,
                        NazwaRaportu,
                        PobieraczRaportów.FormatRaportuText(Format),
                        string.IsNullOrEmpty(DodatkowePrametry) ? string.Empty : string.Format("&{0}", DodatkowePrametry));
            }
        }
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
           // UrlRaportu = "../Reports/Test";
            PobieraczRaportów.WyślijRaport(Page, UrlRaportu, NazwaRaportu, Format);
        }
        public void PobierzRaport(Page page)
        {
            PobieraczRaportów.WyślijRaport(page, UrlRaportu, NazwaRaportu, Format);
        }

    }

    public interface IKontrolkaRaportu
    {
        string NazwaParametruRaportu { get; set; }
        string RaportClientID { get; }
        string Value { get; }
        bool NotRequired //bo domyslnie jest false czy required
        {
            get;
            set;
        }

    }
    public class RaportTextBox : TextBox, IKontrolkaRaportu
    {
        public string RaportClientID { get { return ClientID; } }
        public string NazwaParametruRaportu { get; set; }
        public string Value { get { return this.Text; } }
        public bool NotRequired { get; set; }
    }
    public class RaportBoolCheckBox : CheckBox, IKontrolkaRaportu
    {
        public string RaportClientID { get { return ClientID; } }
        public string NazwaParametruRaportu { get; set; }
        public string Value { get { return this.Checked.ToString(); } }
        public bool NotRequired { get; set; }
    }
    public class RaportDropDownList : DropDownList, IKontrolkaRaportu
    {
        public string RaportClientID { get { return ClientID; } }
        public string NazwaParametruRaportu { get; set; }
        public string Value { get { return this.SelectedIndex >= 0 ? this.SelectedValue : ""; } }
        public bool NotRequired { get; set; }
    }
    public class NumerRejestruTextBox : RaportTextBox
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
          
        }

    }
    public class RaportHiddenField : HiddenField, IKontrolkaRaportu
    {
        public string RaportClientID { get { return ClientID; } }
        public string NazwaParametruRaportu { get; set; }
        public bool NotRequired { get; set; }
    }

    public class PobieraczRaportów
    {
        public static string FormatRaportuText(FormatRaportu Format)
        {
            switch (Format)
            {
                //case FormatRaportu.Brak:
                //    return string.Empty;
                //    break;
                case FormatRaportu.Excel:
                    return "&rs:Format=Excel";
                case FormatRaportu.PDF:
                    return "&rs:Format=PDF";
                case FormatRaportu.Word:
                    return "&rs:Format=Word";
                default:
                    return string.Empty;
            }
        }
        public static string ContentTypeText(FormatRaportu Format)
        {
          //  return string.Empty;
            
            switch (Format)
            {
                //case FormatRaportu.Brak:
                //    return string.Empty;
                case FormatRaportu.Excel:
                    return "application/ms-excel";
                case FormatRaportu.PDF:
                    return "application/pdf";
                case FormatRaportu.Word:
                    return "application/ms-word";
                default:
                    return string.Empty;
            }
        }
        public static string RozszerzenieRaportuText(FormatRaportu Format)
        {
            switch (Format)
            {
                //case FormatRaportu.Brak:
                //    return string.Empty;
                case FormatRaportu.Excel:
                    return ".xls";
                case FormatRaportu.PDF:
                    return ".pdf";
                case FormatRaportu.Word:
                    return ".doc";
                default:
                    return string.Empty;
            }
        }
        private static byte[] PobieżRaport(string Url)
        {
            return PobieżRaport(Url, CredentialCache.DefaultCredentials);
        }
        private static byte[] PobieżRaport(string Url, ICredentials Credentials)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
            req.Method = "GET";

            req.Credentials = Credentials;
            req.Timeout = 1000000;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            return PobieżRaport(resp);
        }

        private static byte[] PobieżRaport(HttpWebResponse resp)
        {
            if (resp.StatusCode != HttpStatusCode.OK)
                return new byte[0];

            Stream pdf = resp.GetResponseStream();

            List<byte[]> chunks = new List<byte[]>();

            int chunkSize = 1024 * 20;
            byte[] chunk = new byte[chunkSize];
            int readCount;

            do
            {
                readCount = pdf.Read(chunk, 0, chunkSize);
                if (readCount > 0)
                {
                    chunks.Add(new byte[readCount]);
                    Array.Copy(chunk, chunks.Last(), readCount);
                }
            }
            while (readCount > 0);

            pdf.Close();

            byte[] fileData = new byte[chunks.Sum(c => c.Length)];
            long destinationIndex = 0;
            chunks.ForEach(c =>
            {
                Array.Copy(c, 0, fileData, destinationIndex, c.Length);
                destinationIndex += c.Length;
            });

            return fileData;
        }
        public static void WyślijRaport(Page page, string url, string NazwaRaportu, FormatRaportu format)
        {
            
                page.Response.Clear();
              //  NazwaRaportu = "WniosekUrlop";
                page.Response.AddHeader("Content-Disposition:", string.Format(" attachment; filename={0}", NazwaRaportu + RozszerzenieRaportuText(format)));
                page.Response.ContentEncoding = System.Text.Encoding.UTF8;

                page.Response.BinaryWrite(PobieraczRaportów.PobieżRaport(url.Replace("\r\n", "%0a")));
                page.Response.ContentType = ContentTypeText(format);
                page.Response.End();
           
        }
        public static void WyślijRaport(Page page, HttpWebResponse Response, string NazwaRaportu, FormatRaportu format)
        {
           
                page.Response.Clear();
              
                page.Response.AddHeader("Content-Disposition:", string.Format(" attachment; filename={0}", NazwaRaportu + RozszerzenieRaportuText(format)));
                page.Response.ContentEncoding = System.Text.Encoding.UTF8;

                page.Response.BinaryWrite(PobieraczRaportów.PobieżRaport(Response));
                page.Response.ContentType = ContentTypeText(format);
                page.Response.End();
          
        }

    }

    public partial class RaportPanel : Panel
    {
        public bool RaportPensum { get; set; }
        private string Error = "";
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (RaportPensum)
            {
                LinkButton HL1 = new LinkButton() { Text = LinkText };
                HL1.Click += new EventHandler(HL1_Click);
                this.Controls.Add(HL1);
            }
            else
            {
                Button HL1 = new Button() { Text = LinkText };
                HL1.Click += new EventHandler(HL1_Click);
                this.Controls.Add(HL1);

                ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(HL1);
            }

        }

        void HL1_Click(object sender, EventArgs e)
        {

            PobierzRaportGET();
        }

        private void PobierzRaportGET()
        {
            string url = "";
          //  url += string.Format("{0}{1}&rs:Command=Render&rs:ClearSession=true{2}", RaportPensum ? DziekSysPage.PensumRaportyUrl : DziekSysPage.DziekanatyRaportyUrl, NazwaRaportu, PobieraczRaportów.FormatRaportuText(Format));

            if (DodajStudentID)
        
            foreach (Control c in this.Controls)
            {
                if (c is IKontrolkaRaportu && (c as IKontrolkaRaportu).NazwaParametruRaportu == "Uwagi")
                {
                }
                if (c is IKontrolkaRaportu && !string.IsNullOrEmpty((c as IKontrolkaRaportu).NazwaParametruRaportu))
                {
                    if ((c as IKontrolkaRaportu).Value.Trim() == "" && (c as IKontrolkaRaportu).NotRequired == false)
                    {
                        this.Error = "proszę uzupełnić wszystkie pola";
                        return;
                    }
                    if ((c as IKontrolkaRaportu).Value.Trim() == "" && (c as IKontrolkaRaportu).NotRequired == true)
                        continue;
                    url += string.Format("&{0}={1}", (c as IKontrolkaRaportu).NazwaParametruRaportu, (c as IKontrolkaRaportu).Value);
                }
            }

          //  HttpContext.Current.Response.Write(url, CzyPDF ? .PDF : WriteContentType.Excel, "x");
            HttpContext.Current.Response.WriteContent(url, CzyPDF ? WriteContentType.PDF : WriteContentType.Excel,"x");
            //PobieraczRaportów.WyślijRaport(Page, url, NazwaRaportu, Format);
        }
        private void PobierzRaportPost()
        {
            string url = "";
            WebPostRequest myPost = new WebPostRequest(string.Format("{0}{1}", "TODO", NazwaRaportu));
            url += string.Format("{0}{1}&rs:Command=Render&rs:ClearSession=true{2}", "TODO", NazwaRaportu, PobieraczRaportów.FormatRaportuText(Format));
            myPost.Add("rs:Command", "Render");
            myPost.Add("rs:ClearSession", "true");
            myPost.Add("rs:Format", myPost.FormatRaportuText(Format));

         
            foreach (Control c in this.Controls)
            {
                if (c is IKontrolkaRaportu && (c as IKontrolkaRaportu).NazwaParametruRaportu == "Uwagi")
                {
                }
                if (c is IKontrolkaRaportu && !string.IsNullOrEmpty((c as IKontrolkaRaportu).NazwaParametruRaportu))
                {
                    if ((c as IKontrolkaRaportu).Value.Trim() == "" && (c as IKontrolkaRaportu).NotRequired == false)
                    {
                        this.Error = "proszę uzupełnić wszystkie pola";
                        return;
                    }
                    if ((c as IKontrolkaRaportu).Value.Trim() == "" && (c as IKontrolkaRaportu).NotRequired == true)
                        continue;
                    myPost.Add((c as IKontrolkaRaportu).NazwaParametruRaportu, (c as IKontrolkaRaportu).Value);
                }
            }
         
            //HttpContext.Current.Response.WriteContent(url, CzyPDF ? WriteContentType.PDF : WriteContentType.Excel);
            PobieraczRaportów.WyślijRaport(Page, myPost.GetResponse(PobieraczRaportów.ContentTypeText(Format)), NazwaRaportu, Format);
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            base.RenderBeginTag(writer);
            if (RaportPensum)
                return;
            if (!string.IsNullOrEmpty(Nazwa))
            {
                writer.RenderBeginTag(HtmlTextWriterTag.H4);
                writer.Write(Nazwa);
                writer.RenderEndTag();
            }
        }
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            if (!RaportPensum)
            {
                if (!string.IsNullOrEmpty(this.Error))
                {
                    writer.Write("<br/><font style='color:red'>" + this.Error + "&nbsp;</font>");
                }
                writer.RenderBeginTag(HtmlTextWriterTag.Hr);
                writer.RenderEndTag();
            }
            base.RenderEndTag(writer);
        }
        public string NazwaRaportu
        {
            get
            {
                return ViewState["NazwaRaportu"] as string ?? "";
            }
            set
            {
                ViewState["NazwaRaportu"] = value;
            }
        }
        public bool DodajStudentID { get; set; }
        public bool CzyPDF
        {
            get
            {
                return Format == FormatRaportu.PDF;
            }
            set
            {
                if (value) Format = FormatRaportu.PDF;
            }
        }
        public bool CzyWord
        {
            get
            {
                return Format == FormatRaportu.Word;
            }
            set
            {
                if (value) Format = FormatRaportu.Word;
            }
        }        private FormatRaportu format = FormatRaportu.PDF;
        public FormatRaportu Format
        {
            get
            {
                if (ViewState["Format"] == null)
                    return FormatRaportu.PDF;
                return (FormatRaportu)ViewState["Format"];
            }

            set
            {
                ViewState["Format"] = value;
            }
        }
        public bool DodajKieruenkID { get; set; }
        public string LinkText { get; set; }
        public string Nazwa { get; set; }
        public bool DodajUwagi { get; set; }
        public bool PolaczWieczoroweZDziennymi { get; set; }

    }

    class WebPostRequest
    {
        WebRequest theRequest;
        HttpWebResponse theResponse;
        System.Collections.ArrayList theQueryData;

        public string FormatRaportuText(FormatRaportu Format)
        {
          
            switch (Format)
            {
                //case FormatRaportu.Brak:
                //    return string.Empty;
                //    break;
                case FormatRaportu.Excel:
                    return "Excel";
                case FormatRaportu.PDF:
                    return "PDF";
                case FormatRaportu.Word:
                    return "Word";
                default:
                    return string.Empty;
            }
        }
        public WebPostRequest(string url)
        {
            theRequest = WebRequest.Create(url);
            theRequest.Method = "POST";
            theQueryData = new System.Collections.ArrayList();
        }

        public void Add(string key, string value)
        {
            theQueryData.Add(String.Format("{0}={1}", key, HttpUtility.UrlEncode(value)));
        }

        public HttpWebResponse GetResponse(string contentType)
        {
            // Set the encoding type
            //theRequest.ContentType = contentType;// "application/x-www-form-urlencoded";
            theRequest.Credentials = CredentialCache.DefaultCredentials;

            // Build a string containing all the parameters
            string Parameters = String.Join("&", (String[])theQueryData.ToArray(typeof(string)));
            theRequest.ContentLength = Parameters.Length;

            // We write the parameters into the request
            StreamWriter sw = new StreamWriter(theRequest.GetRequestStream());
            sw.Write(Parameters);
            sw.Close();

            // Execute the query
            theResponse = (HttpWebResponse)theRequest.GetResponse();
            return theResponse;
            //StreamReader sr = new StreamReader(theResponse.GetResponseStream());
            //return sr.ReadToEnd();
        }

    }
}

